<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Index_Model extends Controller_Index_Base
{    
    public function action_index()
    {
        $model_id = $this->request->param('id') ? $this->request->param('id') : 0;
        $page     = 1;
        $sort     = $this->request->param('sort') ? $this->request->param('sort') : null;
        // TODO проверить урл, чтобы нельзя было расплодить дубли страниц
        
        $model   = ORM::factory('model', $model_id);
        $category = $breadcrumbs = null;
        if ($model->category_id) {
            $category = ORM::factory('category', $model->category_id);
        }
        $reviews = Model_Review::get_reviews($model, $page, false, $sort);
        $reviews = array_slice($reviews, 0, 3);
        
        $model_type = Model_Specs_Abstract::get_model_type($model);
        if ($model_type) {
            $content = new View('index/model/new/index_tpl');
            $specs      = ORM::factory('specs_'.$model_type, $model->id);
            $main_specs = ORM::factory('specs_'.$model_type)->get_specs_full_data_for_main($specs);
            $stat  = ORM::factory('specs_'.$model_type)->get_stat();
            $content->specs       = $specs;
            $content->full_specs  = ORM::factory('specs_'.$model_type)->get_specs_full_data($specs, true);
            $content->stat        = $stat;
            $content->main_specs  = $main_specs;
            $content->available_specs = ORM::factory('specs_'.$model_type)->get_available_specs(true);
            $content->compare_data    = ORM::factory('specs_'.$model_type)->compare_with_same_type($model, $specs);
            
            //call_user_func(array($this, '_index_'.$model_type.'_data'), &$content);  
        } else {            
            $content = new View('index/model/index_tpl');
        }
        
        $competitors = ORM::factory('competitor')->get_competitors($model);
        $prices      = ORM::factory('price')->get_prices($model);
        
        $price = null;
        if (count($prices)) {
            $price = array_slice($prices, 0, 1);
            $price = $price[0];   
        }
        
        $content->competitors = $competitors;
        $content->prices      = $prices;
        $content->price       = $price;
         
        $content->reviews = $reviews;        
        $content->model   = $model;
        $content->category = $category;
        
        $content->pagination = array(
            'page' => $page,
            'per_page' => Model_Review::get_reviews_per_page(),
            'sort' => $sort,
        );  
        $title = $model->name.' : где купить, цена, отзывы, характиристики';
        if ($category->single_form) {
            $title = Model_Main::ucfirst_utf8($category->single_form).' '.$title;    
        } else {
            $title .= ' - '.$category->name;  
        }  
        $description = Helper_Index::get_model_index_description($model);
        $this->print_template($title, $content, $description); 
    }
    
    /**
    * Кастомные главные страницы для товаров из разных категорий
    * 
    * @param mixed $content
    */
    /*protected function _index_camera_data(&$content)
    {
            
    } */
    
    public function action_reviews()
    {
        $model_id = $this->request->param('id') ? $this->request->param('id') : 0;
        $page     = $this->request->param('page') ? $this->request->param('page') : 1;
        $sort     = $this->request->param('sort') ? $this->request->param('sort') : null; 
        // TODO проверить урл, чтобы нельзя было расплодить дубли страниц
        
        $model = ORM::factory('model', $model_id);
        $reviews = Model_Review::get_reviews($model, $page, false, $sort);
        
        $model_type = Model_Specs_Abstract::get_model_type($model);
        if ($model_type) {               
            $content = new View('index/model/new/reviews_tpl');
        } else {
            $content = new View('index/model/reviews_tpl');    
        } 
        
        $content->model   = $model;
        $content->reviews = $reviews;
        $content->pagination = array(
            'page' => $page,
            'per_page' => Model_Review::get_reviews_per_page(),
            'sort' => $sort,
        );
        $category = ORM::factory('category', $model->category_id);
        $title = 'Отзывы о '.$model->name;
        if ($page > 1) {
            $title .= ' - Страница '.$page;   
        }         
        $this->print_template($title.' - '.$category->name, $content); 
    }
    
    public function action_specs()
    {
        $model_id = $this->request->param('id') ? $this->request->param('id') : 0;
        // TODO проверить урл, чтобы нельзя было расплодить дубли страниц
        
        $model = ORM::factory('model', $model_id);
         
        $model_type = Model_Specs_Abstract::get_model_type($model);
        if (!$model_type) {
            // TODO нормальная страница 404
            die();    
        }         
         
        $specs   = ORM::factory('specs_'.$model_type)->get_specs_full_data($model);             
        $content = new View('index/model/new/specs_tpl');
        $content->model = $model;
        $content->specs = $specs;
        $category = ORM::factory('category', $model->category_id); 
        
        $this->print_template('Характеристики '.$model->name.' - '.$category->name, $content); 
    }
    
    public function action_competitors()
    {
        $model_id = $this->request->param('id') ? $this->request->param('id') : 0;
        // TODO проверить урл, чтобы нельзя было расплодить дубли страниц
        
        $model = ORM::factory('model', $model_id);
         
        $model_type = Model_Specs_Abstract::get_model_type($model);
        if (!$model_type) {
            // TODO нормальная страница 404
            die();    
        }         
         
        //$specs   = ORM::factory('specs_'.$model_type)->get_specs_full_data($model);
        $competitors = ORM::factory('competitor')->get_competitors($model);
        $competitors_data = array();
        $model_types = array(); 
        if (count($competitors)) {
            $ids = array();
            foreach ($competitors as $competitor) {
                $ids[] = $competitor->id;    
            }
            $competitor_specs = ORM::factory('specs_'.$model_type)
                                    ->where('id', 'IN', $ids)
                                    ->find_all();
            foreach ($competitor_specs as $competitor_spec) {
                $competitors_data[$competitor_spec->id] = ORM::factory('specs_'.$model_type)->short_compare($competitor_spec, $model);
                $model_types[$competitor_spec->id] = $competitor_spec->camera_type;
            }   
        }
        $sorted_competitors = array();
        foreach ($competitors as $competitor) {
            if (!isset($sorted_competitors[$model_types[$competitor->id]])) {
                $sorted_competitors[$model_types[$competitor->id]] = array();    
            }
            $sorted_competitors[$model_types[$competitor->id]][] = $competitor;    
        }
        
                    
        $content = new View('index/model/new/competitors_tpl');
        $content->model       = $model;
        $content->sorted_competitors = $sorted_competitors;
        $content->competitors_data   = $competitors_data; 
        $content->available_specs    = ORM::factory('specs_'.$model_type)->get_available_specs(true);
        $category = ORM::factory('category', $model->category_id);
        
        $this->print_template('Конкуренты '.$model->name.' - '.$category->name, $content); 
    }
    
    public function action_add_review()
    {
        if (HTTP_Request::POST == $this->request->method()) {
            $rating     = $this->request->post('rating') ? $this->request->post('rating') : null; 
            $experience = $this->request->post('experience') ? $this->request->post('experience') : null; 
            $pluses     = $this->request->post('pluses') ? $this->request->post('pluses') : null; 
            $minuses    = $this->request->post('minuses') ? $this->request->post('minuses') : null; 
            $text       = $this->request->post('text') ? $this->request->post('text') : null; 
            
            $email      = $this->request->post('email') ? $this->request->post('email') : null;      
            $nick       = $this->request->post('nick') ? $this->request->post('nick') : null;  
            $password   = $this->request->post('password') ? $this->request->post('password') : null; 
            
            $model_id   = $this->request->post('model_id') ? $this->request->post('model_id') : null;
                  
            try {
                Model_Main::check_csrf_token();                
                if (!$model_id) {
                    throw new Exception('Не задана модель');
                }
                $model = ORM::factory('model', $model_id);
                
                $user = ORM::factory('user')->add_user($email, $password, $nick);
                $review = ORM::factory('review_recensee')->add_review($model, $user, $text, $pluses, $minuses, $rating, $experience);                               
                $_POST = array();
                 
                Model_Auth::instance()->login($email, $password, true);                    
                Request::current()->redirect('/model/'.$model->id.'-'.Model_Main::translit($model->name).'/sort/date#reviews'); 
            } catch (Exception $e) {
                $message = $e->getMessage();
                if (!$message) {
                    $message = 'Форма заполнена с ошибками!';
                }
                if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                    $message = 'Данный e-mail уже зарегистрирован';
                }
            }
        }
    }
    
    public function action_go()
    {
        $model_id = $this->request->param('model_id') ? $this->request->param('model_id') : 0;
        $price_id = $this->request->param('price_id') ? $this->request->param('price_id') : 0;
        $model    = ORM::factory('model', $model_id);
        $price    = ORM::factory('price', $price_id);
        DB::insert('clicks', array('model_id', 'price_id'))
                    ->values(array($model_id, $price_id))->execute();
        //$url = str_replace('&amp;', '&', $price->url);
        $url = Helper_Index::model_url($model);
        header("Location: ".$url);
        die();
    }
} 
